package org.oneblog.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.oneblog.data.bean.ArticleSolr;
import org.oneblog.data.bean.CategoryFacet;
import org.oneblog.data.bean.HotTag;
import org.oneblog.data.query.ArticleSolrQuery;
import org.oneblog.data.rs.Result;
import org.oneblog.data.service.IArticleSolrService;
import org.oneblog.data.util.BaiduSitePostUtil;
import org.oneblog.data.util.DateFormatUtil;
import org.oneblog.data.util.StringTools;
import org.oneblog.service.AbstractArticleService;
import org.oneblog.service.IArticleService;
import org.oneblog.view.ArticleView;
import org.oneblog.view.RelativeViews;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service("articleService")
public class ArticleServiceImpl extends AbstractArticleService implements IArticleService {

	@Cacheable(value="blogCache", key = "#solrQuery.key()")
    @Override
    public Result<ArticleView> queryArticles(ArticleSolrQuery solrQuery) {
        
        Result<ArticleView> result = new Result<>();
        
        Result<ArticleSolr> articles = articleSolrService.queryArticles(solrQuery);
        
        result.setTotal(articles.getTotal());
        result.setList(convertFrom(articles.getList()));
        
        //生成分页
        result.createPages(solrQuery.getPageNo(), solrQuery.getPageSize());

//        System.out.println("queryArticles " + JSON.toJSONString(result));
        
        return result;
    }

    private List<ArticleView> convertFrom(List<ArticleSolr> list) {
        if(CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<ArticleView> views = new ArrayList<ArticleView>(list.size());
        for(ArticleSolr s : list) {
            views.add(create(s));
        }
        return views;
    }
    
    ArticleView create(ArticleSolr s) {
        ArticleView v = new ArticleView();
        v.setId(s.getArticleId());
        v.setTitle(s.getArticleTitle());
        v.setContent(s.getArticleContent());//需要进行摘要生成
        v.setTags(s.getTags());
        v.setUpdateTime(s.getUpdateTime());
        v.setViewCount(s.getBrowserCount());
        v.setUpdateTimeString(DateFormatUtil.formatOnDay(new Date(s.getUpdateTime())));
        v.setSrcType(s.getSrcType());
        String imgUrl = s.getThumbnailImgUrl();
        if(StringUtils.isNotBlank(imgUrl)) {
            v.setThumbnailImgUrl(imgUrl);
        }
        v.setGoodCount(s.getGoodCount());
        return v;
    }
    

    @Cacheable(value="dayCache", key = "'allHotTags'")
    @Override
    public List<HotTag> allHotTags() {
        
        return articleSolrService.getHotTags();
    }
    @Cacheable(value="dayCache", key = "'hotArticles'")
    @Override
    public List<ArticleView> hotArticles() {

        List<ArticleSolr> articles = articleSolrService.queryHotArticles(8);
        
        List<ArticleView> list = convertFrom(articles);
        
        return list;
    }

    @Cacheable(value="dayCache", key = "'priorityArticles'")
    @Override
    public List<ArticleView> priorityArticles() {
        List<ArticleSolr> articles = articleSolrService.queryPriority(8);
        
        List<ArticleView> list = convertFrom(articles);
        
        return list;
    }
    
    @Override
    public int upsertArticle(ArticleSolr articleSolr, Long userId) {
        
        articleSolr.setThumbnailImgUrl(getImgUrl(articleSolr.getArticleContent()));
        
        String id = articleSolr.getArticleId();
        if(StringUtils.isBlank(id)) {//新增
            articleSolr.setArticleId(StringTools.randomUUID());
            articleSolr.setUpdateUserId(userId);
            articleSolr.setCreateUserId(userId);
            Long current = System.currentTimeMillis();
            articleSolr.setUpdateTime(current);
            articleSolr.setCreateTime(current);
            return articleSolrService.insertArticles(articleSolr);
        } else {//更新
            ArticleSolr old = articleSolrService.getById(id);
            if(old == null) {
                return 0;
            }
            
            //更新覆盖
            articleSolr = setUpdate(articleSolr, old);
            articleSolr.setUpdateUserId(userId);
            return articleSolrService.updateArticles(articleSolr);
        }
    }
    
    //将更新后的内容覆盖到旧数据，然后更新
    private ArticleSolr setUpdate(ArticleSolr articleSolr, ArticleSolr old) {
        Long current = System.currentTimeMillis();
        
        old.setUpdateTime(current);
        old.setArticleTitle(articleSolr.getArticleTitle());
        old.setArticleContent(articleSolr.getArticleContent());
        old.setCategoryId(articleSolr.getCategoryId());
        old.setSrcType(articleSolr.getSrcType());
        old.setTags(articleSolr.getTags());
        old.setPriority(articleSolr.getPriority());
        old.setThumbnailImgUrl(articleSolr.getThumbnailImgUrl());
        
        return old;
    }
    
    @Override
    public ArticleView detail(String articleId) {
        
        ArticleSolr article = articleSolrService.getById(articleId);
        
        if(article == null) {
            return new ArticleView();
        }
        
        articleSolrService.updateArticleBroswerCount(articleId, article.getBrowserCount() + 1);
        
        return create(article);
    }
    
    @Override
    public CategoryFacet categoryFacet() {
    	
    	return articleSolrService.categoryFacet();
    }

    @Cacheable(value="dayCache", key = "'relativeArticles_' + #id")
    @Override
    public List<ArticleView> relativeArticles(String id) {
        if(StringUtils.isBlank(id)) {
            return null;
        }
        ArticleSolr article = articleSolrService.getById(id);
        if(article == null) {
            return null;
        }
        
        String keyword = article.getArticleTitle();
        
        List<String> tags = article.getTags();
        
        return convertFrom(articleSolrService.queryRelativeArticles(id, keyword, tags));
    }

    @Override
    public RelativeViews getRelativeViews(String id) {
        
        return null;
    }
    
    @Override
    public void pushUrlToBaidu() {

        List<String> urls = new ArrayList<String>();
        urls.add("https://www.oomabc.com/list");
        
        List<String> ids = articleSolrService.getAllArticleIds();
        if(!CollectionUtils.isEmpty(ids)) {
            for(String id : ids) {
                urls.add("https://www.oomabc.com/articledetail?atclid=" + id);
            }
        }

        try {
            String s = BaiduSitePostUtil.post("http://data.zz.baidu.com/urls?site=https://www.oomabc.com&token=kuhkoaCn8ehIYbvQ", urls.toArray(new String[urls.size()]));
            
            System.out.println(s);
        } catch (Exception e) {
            
        }
             
    }

    @Cacheable(value="dayCache", key = "'setGoot_' + #articleId + '_' + #outIp + '_' + #localIp")
    @Override
    public int setGood(String articleId, String outIp, String localIp) {
        return articleSolrService.increaseGoodCount(articleId);
    }
    
    @Resource(name = "articleSolrService")
    private IArticleSolrService articleSolrService;
}
